<template>
  <div class="w-[900px] my-[15px]">
    <div class="border-bottom">
      <div class="item">
        <div class="label">
          <div class="flex flex-col justify-center items-center">
            <span class="mb-[4px]"><i class="required">✲</i>选择游戏</span>
            <el-switch size="large" v-model="state.master" @change="handelMasterSwitch" />
          </div>
        </div>
        <div class="box !pt-[10px]">
          <div v-for="item in state.games" :key="item.LotteryId" class="game">
            <span class="text-[14px]">{{ item.Name }}</span>
            <el-switch
              size="large"
              v-model="item.Checked"
              @change="handelSubSwitch(item.Checked!, item.LotteryId)"
            />
          </div>
        </div>
      </div>
      <div class="item">
        <div class="label">红包类型</div>
        <div class="box">
          <el-switch
            v-model="form.Type"
            inline-prompt
            size="large"
            active-text="等额"
            inactive-text="随机"
            :active-value="2"
            :inactive-value="1"
          />
        </div>
      </div>
      <div class="item">
        <div class="label"><i class="required">✲</i>会员列表</div>
        <div class="box">
          <template v-if="uid">
            <el-input :value="username" disabled></el-input>
          </template>
          <template v-else>
            <div class="!w-[200px]">
              <el-select
                v-model="state.user"
                :multiple="false"
                filterable
                remote
                reserve-keyword
                placeholder="请输入用户名搜索"
                remote-show-suffix
                :remote-method="remoteMethod"
                :loading="state.loading"
              >
                <el-option
                  v-for="item in state.options"
                  :key="item.UserId"
                  :label="item.Name"
                  :value="item.UserId"
                />
              </el-select>
            </div>
          </template>
        </div>
      </div>
      <div class="item">
        <div class="label"><i class="required">✲</i><span>红包积分</span></div>
        <div class="box">
          <div class="!w-[400px]">
            <el-input v-model="form.Amount" type="number"></el-input>
          </div>
        </div>
      </div>
      <div class="item">
        <div class="label"><i class="required">✲</i><span>红包数量</span></div>
        <div class="box">
          <div class="!w-[400px]">
            <el-input :disabled="!!props.username" v-model="form.Count" type="number"></el-input>
          </div>
        </div>
      </div>
      <div class="item">
        <div class="label">最小流水</div>
        <div class="box">
          <div class="!w-[400px]">
            <el-input v-model="form.MiniBet" type="number"></el-input>
          </div>
        </div>
      </div>
      <div class="item">
        <div class="label">红包备注</div>
        <div class="box">
          <div class="!w-[400px]">
            <el-input v-model="form.Remark"></el-input>
          </div>
        </div>
      </div>
      <div class="item">
        <div class="label">到期时间</div>
        <div class="box">
          <div class="!w-[400px]">
            <el-date-picker v-model="form.EndTime" type="datetime" placeholder="选择到期时间" />
          </div>
        </div>
      </div>
    </div>
    <div class="flex justify-end items-center mt-[15px]">
      <div>
        <el-button
          :disabled="state.updating"
          :loading="state.updating"
          type="primary"
          @click="confirm"
          >确 定</el-button
        >
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import $bus from "@/utils/bus";
import { message } from "@/utils/message";
import { debounce } from "lodash-es";
import { useGameStore } from "@/store/modules/game";
import { storeToRefs } from "pinia";
import { reqSendRedPacket, reqUserQuery } from "@/api/user";
import moment from "moment";

interface FormState {
  GameList: number[];
  Type: number;
  Amount: number | null;
  Count: number | null;
  MiniBet: number | null;
  Remark: string;
  EndTime: any;
}

const props = withDefaults(
  defineProps<{
    uid?: number;
    username?: string;
    type: "add" | "edit";
  }>(),
  {}
);
const gameStore = useGameStore();
const { gameTotal } = storeToRefs(gameStore);
// 获取当前时间
let currentDate = new Date();

// 获取明天的日期
let tomorrowDate = new Date(currentDate);
tomorrowDate.setDate(currentDate.getDate() + 1);

// 将时间设置为零点
tomorrowDate.setHours(0, 0, 0, 0);

const defaultForm = {
  GameList: [],
  Type: 1,
  Amount: null,
  Count: null,
  MiniBet: 0,
  Remark: "恭喜发财！大吉大利！",
  EndTime: tomorrowDate
};
const emit = defineEmits(["update"]);
const state = reactive({
  updating: false,
  isShow: false,
  master: false,
  games: <GameLeftMo[]>[],
  user: "",
  loading: false,
  options: <{ UserId: number; Name: string }[]>[]
});
const form = reactive<FormState>({ ...defaultForm });

const reset = () => {
  form.GameList = [];
  form.Type = 1;
  form.Amount = null;
  form.Count = null;
  form.MiniBet = 0;
  form.Remark = "恭喜发财！大吉大利！";
  form.EndTime = tomorrowDate;

  state.master = false;
  state.games.forEach(item => {
    item.Checked = false;
  });
};

const initData = () => {
  state.games = gameTotal.value.map(item => ({ ...item, Checked: false }));
  if (props.type == "edit") {
  } else {
    form.Count = props.uid ? 1 : null;
    form.Type = 2;
  }
};

const handelMasterSwitch = (flag: boolean) => {
  form.GameList = [];
  state.games.forEach(item => {
    item.Checked = flag;
    handelSubSwitch(flag, item.LotteryId);
  });
};

const handelSubSwitch = (flag: boolean, id: number) => {
  if (flag) {
    form.GameList.push(id);
  } else {
    form.GameList = form.GameList.filter(item => item !== id);
  }
};

const remoteMethod = async (query: string) => {
  if (query) {
    state.loading = true;
    const res = await reqUserQuery({
      Name: query
    });
    state.options = res.data;
    state.loading = false;
  } else {
    state.options = [];
  }
};

const confirm = debounce(
  async () => {
    const list = form.GameList.map(num => `{${num}}`).join("");
    if (form.GameList.length == 0) {
      return message.warning("请选择游戏");
    }
    if (!props.uid && !state.user) {
      return message.warning("请选择用户");
    }
    if (!form.Amount) {
      return message.warning("请输入红包积分");
    }
    if (!form.Count) {
      return message.warning("请输入红包数量");
    }
    if (!form.MiniBet && form.MiniBet !== 0) {
      return message.warning("请输入最小流水");
    }
    if (!form.EndTime) {
      return message.warning("请选择到期时间");
    }
    const data = {
      GameList: list,
      Type: form.Type,
      UserId: <number | null>null,
      Amount: Number(form.Amount),
      Count: Number(form.Count),
      MiniBet: Number(form.MiniBet),
      Remark: form.Remark,
      EndTime: moment(form.EndTime).format("YYYY-MM-DD HH:mm:ss")
    };
    if (props.uid) {
      data["UserId"] = props.uid;
    } else {
      data["UserId"] = Number(state.user);
    }
    try {
      state.updating = true;
      await reqSendRedPacket(data);
      state.updating = false;
      state.user = "";
      state.options = [];
      $bus.emit("redpack-send-success");
      emit("update");
      message.success("发送成功");
      setTimeout(() => {
        reset();
      }, 200);
    } catch (error) {
      state.updating = false;
      console.log(error);
    }
  },
  500,
  { leading: true, trailing: false }
);
onMounted(() => {
  initData();
});
</script>
<style scoped lang="scss">
:deep(.el-dialog__body) {
  padding: 15px;
}
.item {
  display: flex;
  overflow: hidden;
  &:last-child {
    margin-bottom: 0;
  }
  .label {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 120px;
    border: 1px solid #ddd;
    border-right: 0;
    border-bottom: 0;
    font-size: 14px;
    color: #666;
  }
  .box {
    flex: 1;
    min-height: 36px;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    padding: 2px 6px;
    border: 1px solid #ddd;
    border-bottom: 0;
    font-size: 13px;
    i {
      margin: 0 2px;
    }
    .game {
      display: flex;
      align-items: center;
      width: 25%;
      margin-bottom: 5px;
      > span {
        width: 90px;
        margin-left: 5px;
        font-size: 13px;
      }
    }
    :deep() {
      .el-input {
        --el-input-bg-color: #f4f7f8;
      }
      .el-select {
        width: 100% !important;
      }
      .el-date-editor.el-input {
        --el-input-bg-color: #f4f7f8;
        width: 100% !important;
      }
    }
  }
}
</style>
